package factory

import (
	"git.multiverse.io/eventkit/dxc-server/config"
	v2 "git.multiverse.io/eventkit/dxc-server/config/v2"
	"git.multiverse.io/eventkit/dxc-server/constant"
	"git.multiverse.io/framework/log"
	"github.com/go-errors/errors"
	"strings"
)

type LoaderFactoryImpl struct{}

func (l *LoaderFactoryImpl) CreateConfigLoader(version string) config.Loader {
	var loader config.Loader
	switch version {
	case "v1":
		{
			loader = &v2.Loader{}
		}
	default:
		{
			loader = &v2.Loader{}
		}
	}

	return loader
}

func InitDxcServerConfig(filepath string) (err error) {
	log.Infosf("start init dxc server config, file path[%s]...", filepath)

	factory := &LoaderFactoryImpl{}
	var version string
	if strings.HasSuffix(filepath, "conf") {
		version = "v1"
	} else {
		version = "v2"
	}
	loader := factory.CreateConfigLoader(version)
	if cfg, err := loader.LoadConfig(filepath); nil != err {
		return err
	} else {
		config.Cfg = cfg
	}

	// check env
	if config.Cfg.NodeId == "" {
		return errors.Errorf("cannot found env key `%s`", constant.ENV_NODE_ID_KEY)
	}
	if config.Cfg.InstanceId == "" {
		return errors.Errorf("cannot found env key `%s`", constant.ENV_INSTANCE_ID_KEY)
	}

	log.Infosf("init dxc server config successfully, DxcConfig=[%++v]!", config.Cfg)
	return
}
